import cloudbase, { IBaseRes } from "@cloudbase/node-sdk";
import { dealDbMessage } from "./util";
import config from "./config";
export const app = cloudbase.init(config.cloudConfig);
const db = app.database();
const _ = db.command;
// lookup 连表  https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.lookup.html#%E7%A4%BA%E4%BE%8B
const statusMenu = {
  err: 400,
};
interface whereProps {
  pageSize: number;
  pageIndex: number;
  [key: string]: any;
}
interface optionsProp {
  where?: whereProps | string | any;
  field?: Record<string, unknown>;
  needTotal?: boolean;
}
const DbUtil = {
  db,
  _,
  async colectionList() {
    // const res = await db.serverDate;
    // console.log(res);
  },
  async createCollection(collection: string): Promise<IBaseRes> {
    const res = await db.createCollection(collection);
    return res;
  },

  async query(collection: string, options: optionsProp = {}) {
    //field 表示要返回的字段
    let { where = {}, field = {}, needTotal = true } = options;
    let conn:
      | cloudbase.Database.CollectionReference
      | cloudbase.Database.Query = await db.collection(collection);
    if (typeof where === "string") {
      // 处理传递的参数有特殊字符
      where = eval(`(${where})`);
    }
    let { pageIndex = 1, pageSize = 10, ...others } = where;
    delete others.collectoin;
    conn = await conn.where(others as Object);
    conn = await conn
      .skip((Number(pageIndex) - 1) * pageSize)
      .limit(Number(pageSize));

    const res = await conn.field(field).get();
    let count = 0;
    if (needTotal) {
      count =
        (await (await db.collection(collection).where(others).count()).total) ||
        0;
    }
    const respon = dealDbMessage(res.data, 0, "", {
      pageInfo: {
        total: count,
      },
    });
    return respon;
  },
  async insert(collection: string, data = {}) {
    const res = await db.collection(collection).add(data);
    if (res.id) {
      return dealDbMessage(res);
    } else {
      return dealDbMessage("", statusMenu.err, "插入失败");
    }
  },
  async update(collection: string, id: string, data: any = {}) {
    try {
      if (data._id) {
        delete data._id;
        delete data.id;
      }
    } catch (err) {
      console.log(err);
    }

    const res = await db.collection(collection).doc(id).update(data);
    if (res.requestId && res.updated && res.updated > -1) {
      return dealDbMessage(res.updated);
    } else {
      return dealDbMessage(res.updated, statusMenu.err);
    }
  },
  async delete(collection: string, id: string) {
    const res = await db.collection(collection).doc(id).remove();
    if (res.deleted > -1) {
      return dealDbMessage(res.deleted);
    } else {
      return dealDbMessage(res.deleted, statusMenu.err, "没有找到该数据");
    }
  },
};
export default DbUtil;
